# -*- coding:utf-8 -*-

__author__ = 'zhangdakang@unisound.com'
__date__ = '2015.07.13 ~ 2016.12.2'

import re
import sys
import time
from sys import argv
from ConfigParser import ConfigParser as Parser
from project_tools.domainConvertor import DomainConvertor
from project_tools.caseRunner import run_all
from project_tools.resultHandler import ResultHandler
from ConfigParser import ConfigParser


# 重写ConfigParser, 写入配置时需要大小写敏感(默认不敏感)
class CaseSensitiveConfigParser(ConfigParser):
    def __init__(self):
        ConfigParser.__init__(self)

    def optionxform(self, optionstr):
        return optionstr


def init_conf(conf_file):
    """
    1. 可以传3个参数: <ip:port>, <deploy_file>, <thread_num>
    2. 第三个参数默认线上域名5, 线下用30, 可指定.
    """
    deploy_file = ''
    ip, port, thread = '', '80', 30

    if len(argv) < 3:
        print '''    usage: python usk_skill_regression.py IP:port deploy_file [thread_num]
    Example: python usk_skill_regression.py 172.20.61.217:8080 conf/nlu_manage_online.txt 
             python -u usk_skill_regression.py 172.18.10.69:8080 conf/nlu_manage_uat.txt  10

            '''
        sys.exit(1)
    if len(argv) >= 3:
        if ':' in argv[1]:
            ip, port = argv[1].split(':', 1)
        else:
            ip = argv[1]
        deploy_file = argv[2]
        if 'conf' not in argv[2]:
            deploy_file = './conf/%s' % argv[2]

        if len(argv) >= 4:
            thread = int(argv[3])
        if 'hivoice.cn' in argv[1] and thread > 5:  # 生产环境最大5并发.
            thread = 5

    config = CaseSensitiveConfigParser()
    config.read(conf_file)
    config.set("Test_Setting", "ip", ip)
    config.set("Test_Setting", "port", port)
    config.set("Test_Setting", "deploy_file", deploy_file)
    config.set("Test_Setting", "thread_num", thread)
    config.write(open(conf_file, "w"))


def show_elapsed_time(begin):
    fr = time.strftime("%H:%M:%S", time.localtime(begin))
    to = time.strftime("%H:%M:%S", time.localtime(time.time()))
    elapsed_sec = time.time() - begin

    m = elapsed_sec / 60
    s = elapsed_sec % 60
    print "Elapsed_Time: %d'%d'' (%s ~ %s)" % (m, s, fr, to)


if __name__ == '__main__':
    """ 1. 转换用例: 按照领域(一个文件)生成领域列表 >> 向领域中添加用例(一个领域对应一个用例列表).
        2. 运行用例: 运行并记录每个领域*用例的结果(url返回结果, 响应时间, 是否Pass等).
        3. 计算结果: 给出准确率, 输出用例信息到log, 记录每次版本(封版/每天/临时)记录.
        python usk_skill_regression.py 172.20.61.217:8080 conf/nlu_manage_online.txt
        python -u usk_skill_regression.py 172.18.10.69:8080 conf/nlu_manage_uat.txt
    """
    conf_file = './conf/usk_regression.conf'
    init_conf(conf_file)

    begin = time.time()
    domain_convertor = DomainConvertor(conf_file)
    result_handler = ResultHandler(conf_file)
    domain_list = domain_convertor.get_domain_list()

    run_all(domain_list)

    result_handler.init_logs()
    result_handler.calc_test_result(domain_list)
    show_elapsed_time(begin)
